<script setup lang="ts">
import { h, onMounted, reactive, ref, watch } from 'vue';
import type { DataTableColumns, DataTableRowKey } from 'naive-ui';
import { NImage } from 'naive-ui';
import { getAllFolder, getImageDataByTenantAction, getLabelList } from '@/service/api';

defineOptions({
  name: 'SelectImageDrawer'
});

interface Emits {
  (e: 'confirmImage'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

interface FormData {
  folderId: string;
  folderName: string;
  imgType: string;
  imgTypeName: string;
}

const formData = reactive<FormData>({
  folderId: '',
  folderName: '',
  imgType: '',
  imgTypeName: ''
});

const folderData = ref<any[]>([]);
const imgTabs = ref<any[]>([]);
const imgDataList = ref<any[]>([]); // 图片列表数据
const selectImgList = ref<any[]>([]); // 已选图片列表
const checkedRowKeysRef = ref<DataTableRowKey[]>([]);

watch(
  () => visible.value,
  value => {
    if (value) {
      imgDataList.value = [];
      selectImgList.value = [];
      checkedRowKeysRef.value = [];

      if (folderData.value.length > 0) {
        formData.folderId = folderData.value[0].id;
      }

      if (imgTabs.value.length > 0) {
        formData.imgType = imgTabs.value[0].dictValue;
      }

      searchClick();
    }
  }
);

onMounted(() => {
  getAllFolderData();
});

// 获取所有公司文件夹
async function getAllFolderData() {
  const params: any = {
    parentId: 0,
    pageNum: 1,
    pageSize: 9999
  };
  const { data, error } = await getAllFolder(params);
  if (!error) {
    folderData.value = data.list;
    if (folderData.value.length > 0) {
      formData.folderId = folderData.value[0].id;
    }

    await getImageAllLabelData();
  }
}

// 获取图片标签类型信息
async function getImageAllLabelData() {
  const { data, error } = await getLabelList();

  if (!error) {
    imgTabs.value = data;
    if (imgTabs.value.length > 0) {
      formData.imgType = imgTabs.value[0].dictValue;
    }

    await searchClick();
  }
}

function closeDrawer() {
  visible.value = false;
}

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;
const otherUrl = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

interface RowData {
  id: number;
  fileCname: string;
  folderId: number;
  fileType: number;
  filePath: string;
}

const columns: DataTableColumns<RowData> = [
  {
    type: 'selection'
  },
  {
    title: '公司文件夹',
    key: 'folderId',
    align: 'center',
    render: (item: RowData) => {
      return formData.folderName;
    }
  },
  {
    title: '照片类型',
    key: 'fileType',
    align: 'center',
    render: (item: RowData) => {
      return formData.imgTypeName;
    }
  },
  {
    title: '照片封面',
    key: 'filePath',
    align: 'center',
    render: (item: RowData) => {
      if (item.filePath) {
        return h('div', { class: 'flex justify-center h-50px' }, [
          h(NImage, {
            height: 50,
            width: 50,
            objectFit: 'cover',
            src: otherUrl.imgUrl + item.filePath,
            alt: item.fileCname
          })
        ]);
      }
      return null;
    }
  },
  {
    title: '照片名称',
    key: 'fileCname',
    align: 'center'
  }
];

const selectImageAction = (rowKeys: any, rows: object[], action: 'check' | 'uncheck' | 'checkAll' | 'uncheckAll') => {
  checkedRowKeysRef.value = rowKeys;

  if (action.action === 'check') {
    if (!selectImgList.value.includes(action.row)) {
      selectImgList.value.unshift(action.row);
    }
  } else if (action.action === 'uncheck') {
    const index = selectImgList.value.findIndex((item: any) => item.id === action.row.id);
    if (index !== -1) {
      selectImgList.value.splice(index, 1);
    }
  } else if (action.action === 'checkAll') {
    selectImgList.value = mergeAndDistinct(imgDataList.value, selectImgList.value);
  } else if (action.action === 'uncheckAll') {
    imgDataList.value.forEach((item: any) => {
      const index = selectImgList.value.findIndex((i: any) => i.id === item.id);
      if (index !== -1) {
        selectImgList.value.splice(index, 1);
      }
    });
  }
};

// 数组合并去重
function mergeAndDistinct(arr1: any[], arr2: any[]) {
  const merged: any[] = arr1.concat(arr2);
  return Array.from(new Set(merged));
}

// 搜索
async function searchClick() {
  const params: any = {
    folderId: formData.folderId,
    picType: formData.imgType,
    pageNum: 1,
    pageSize: 10
  };
  const { data, error } = await getImageDataByTenantAction(params);
  if (!error) {
    imgDataList.value = data.list;

    folderData.value.forEach(item => {
      if (item.id === formData.folderId) {
        formData.folderName = item.folderName;
      }
    });

    imgTabs.value.forEach(item => {
      if (item.dictValue === formData.imgType) {
        formData.imgTypeName = item.dictLabel;
      }
    });
  }
}

// 保存编写
async function confirmClick() {
  emit('confirmImage', selectImgList.value);
  closeDrawer();
}
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :mask-closable="true" width="1000px">
    <NDrawerContent
      title="添加图片"
      :header-style="{ fontSize: '18px', fontWeight: 'bold' }"
      :body-content-style="{ background: '#E8ECFD', height: '100%', padding: '20px 25px' }"
      :native-scrollbar="false"
      :closable="true"
    >
      <NCard>
        <NForm :model="formData" inline label-placement="left">
          <NFormItem
            label="公司文件夹"
            label-style="font-size: 20px; font-family: HarmonyOS Sans SC; font-weight: bold;"
          >
            <NSelect
              v-model:value="formData.folderId"
              :options="folderData"
              label-field="folderName"
              value-field="id"
              :consistent-menu-width="false"
              class="w-240px"
            />
          </NFormItem>
          <NFormItem label="照片类型" label-style="font-size: 20px; font-family: HarmonyOS Sans SC; font-weight: bold;">
            <NSelect
              v-model:value="formData.imgType"
              :options="imgTabs"
              label-field="dictLabel"
              value-field="dictValue"
              :consistent-menu-width="false"
              :to="false"
              class="w-120px"
            />
          </NFormItem>
          <NFormItem>
            <NButton class="search-btn" strong quaternary @click="searchClick">搜索</NButton>
          </NFormItem>
        </NForm>
        <NDataTable
          :columns="columns"
          :data="imgDataList"
          :row-key="(item: any) => item.id"
          max-height="100%"
          striped
          :checked-row-keys="checkedRowKeysRef"
          @update-checked-row-keys="selectImageAction"
        />
      </NCard>
      <template #footer>
        <div class="ml-30px w-full flex-col">
          <span class="footer-title">已选择照片</span>
          <NScrollbar v-if="selectImgList.length > 0" class="max-h-240px flex-col">
            <div v-for="item in selectImgList" :key="item.id" class="img-title">
              {{ item.fileCname }}
            </div>
          </NScrollbar>
          <NEmpty v-else class="mt-20px" description="暂无选择照片" />
          <NSpace class="mt-20px w-full" justify="end" :size="16">
            <NButton class="cancel-btn" strong quaternary @click="closeDrawer">取消</NButton>
            <NButton class="submit-btn" strong quaternary @click="confirmClick">确认</NButton>
          </NSpace>
        </div>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped lang="scss">
.search-btn {
  width: 80px;
  height: 32px;
  background: white;
  border-radius: 4px;
  font-weight: 400;
  font-size: 16px;
  color: #7c73f3;
  line-height: 32px;
  border: 1px solid #7c73f3;
}
.footer-title {
  font-size: 22px;
  line-height: 40px;
  font-weight: bold;
  margin-bottom: 10px;
}
.img-title {
  font-size: 16px;
  line-height: 25px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 5px;
}
.img-title:hover {
  background: rgba(#836fff, 0.1);
}
.cancel-btn {
  width: 120px;
  height: 42px;
  background: white;
  border-radius: 4px;
  font-weight: 400;
  font-size: 16px;
  color: #666666;
  line-height: 42px;
  border: 1px solid #666666;
}
.submit-btn {
  width: 120px;
  height: 42px;
  background: linear-gradient(180deg, #e877ae, #7c73f3);
  border-radius: 4px;
  font-weight: 400;
  font-size: 16px;
  color: #ffffff;
  line-height: 42px;
  border: none;
}
</style>
